package zmee.pur.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class DealToFinPlugin extends AbstractOperationServicePlugIn {
    private static Log logger = LogFactory.getLog(DealToFinPlugin.class);
    private String serverurl = "";

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        if (this.operationResult.isSuccess()) {
            DynamicObject[] dataEntities = e.getDataEntities();
            List<String> list=new ArrayList<>();
            for (DynamicObject dataEntity : dataEntities) {
                String Pkid = dataEntity.getPkValue().toString();
                String billno = "";
                if (dataEntity.getString("billno")!=null){
                    billno = dataEntity.getString("billno");
                }
                String context = "单据号："+billno+"已办结";
                //付款申请单与业财应付单
                if (billno!=null){
                    if (billno.contains("GXFKS")){
                        QFilter qFilter = new QFilter("billno", "=", billno);
                        DynamicObject gxfks = BusinessDataServiceHelper.loadSingle("ap_payapply", "creator,zjmi_department,applycause,applyamount,paycurrency", new QFilter[]{qFilter});
                        if (gxfks!=null){
                            //部门
                            String department = "";
                            DynamicObject zjmi_department = gxfks.getDynamicObject("zjmi_department");
                            if (zjmi_department!=null){
                                department = zjmi_department.getString("name");
                            }
                            //网银附言
                            String applycause = gxfks.getString("applycause");
                            //金额
                            String applyamount = gxfks.getString("applyamount");
                            int i = applyamount.indexOf(".");
                            String aNumber = applyamount.substring(0,i+3);
                            //创建人
                            String creator = "";
                            DynamicObject user = gxfks.getDynamicObject("creator");
                            if (user!=null){
                                creator = user.getString("name");
                            }
                            //币别
                            String number = "";
                            DynamicObject paycurrency = gxfks.getDynamicObject("paycurrency");
                            if (paycurrency!=null){
                                number = paycurrency.getString("number");
                            }
                            context = department+"-"+creator+"-"+applycause+"-"+number+aNumber+"";
                        }else{
                            context = "单据号："+billno+"已办结";
                        }
                    }else if (billno.contains("GXCWF")){
                        QFilter qFilter = new QFilter("billno", "=", billno);
                        DynamicObject gxcwf = BusinessDataServiceHelper.loadSingle("ap_finapbill", "creator,department,zjmi_checkboxfield,billtypeid,zjmi_applycause,pricetaxtotal,zjmi_payamountsum,currency", new QFilter[]{qFilter});
                        if (gxcwf!=null){
                            //部门
                            String department = "";
                            DynamicObject zjmi_department = gxcwf.getDynamicObject("department");
                            if (zjmi_department!=null){
                                department = zjmi_department.getString("name");
                            }
                            logger.info("DealToFin:istrue"+zjmi_department);
                            //审核后自动生成付款申请并提交
                            String istrue = gxcwf.getString("zjmi_checkboxfield");
                            logger.info("DealToFin:istrue"+istrue);
                            //应付总金额
                            String pricetaxtotal = gxcwf.getString("pricetaxtotal");
                            int i = pricetaxtotal.indexOf(".");
                            String pNumber = pricetaxtotal.substring(0,i+3);
                            logger.info("DealToFin:pNumber"+pNumber);

                            //本次付款金额
                            String zjmi_payamountsum = gxcwf.getString("zjmi_payamountsum");
                            int index = zjmi_payamountsum.indexOf(".");
                            String intNumber = zjmi_payamountsum.substring(0,index+3);
                            logger.info("DealToFin:intNumber"+intNumber);

                            //单据类型
                            DynamicObject billtypeid = gxcwf.getDynamicObject("billtypeid");
                            String name = billtypeid.getString("name");
                            logger.info("DealToFin:name"+name);
                            //网银附言
                            String applycause = gxcwf.getString("zjmi_applycause");
                            logger.info("DealToFin:zjmi_applycause"+applycause);

                            //创建人
                            String creator = "";
                            DynamicObject user = gxcwf.getDynamicObject("creator");
                            if (user!=null){
                                creator = user.getString("name");
                            }
                            //币别
                            String number = "";
                            DynamicObject paycurrency = gxcwf.getDynamicObject("currency");
                            if (paycurrency!=null){
                                number = paycurrency.getString("number");
                            }

                            if (istrue.equals("true")){
                                //财务应付单（付款）
                                context = department+"-"+creator+"-"+applycause+"-"+number+intNumber+"";
                            }else if (istrue.equals("false")){
                                //财务应付单
                                context = department+"-"+creator+"-"+name+"-"+number+pNumber+"";
                            }
                        }else{
                            context = "单据号："+billno+"已办结";
                        }
                    }else{
                        context = "单据号："+billno+"已办结";
                    }
                }else {
                    context = "单据号："+billno+"已办结";
                }

                //

                QFilter qFilter = new QFilter("businesskey", QCP.equals,Pkid);
                DynamicObject flow = BusinessDataServiceHelper.loadSingle("wf_execution", "creatorid,processinstanceid", new QFilter[]{qFilter});
                //流程实例为空即流程结束
                if (flow==null){
                    QFilter qFilter1 = new QFilter("zmee_billnumber",QCP.equals,billno);
                    DynamicObject[] f = BusinessDataServiceHelper.load("zmee_log_oapush",
                            "zjmi_flowid,creator",new QFilter[]{qFilter1},"zmee_createdate desc");
                    //单据没进流程
                    if (f.length==0){
                        break;
                    }
                    String flowid = f[0].getString("zmee_flowid");

                    DynamicObject creater = (DynamicObject) f[0].get("creator");
                    Object creatorid = creater.getPkValue();
                    DynamicObject user = BusinessDataServiceHelper.loadSingle(creatorid,"bos_user");
                    String creator =user.getString("username");

                    dealToFin(flowid,creator,context);
                    break;
                }
                String flowid = "hn_opc"+flow.getString("processinstanceid");
                DynamicObject object = (DynamicObject) flow.get("creatorid");
                Object creatorid = object.getPkValue();
                QFilter qFilter1 = new QFilter("businesskey", QCP.equals,Pkid);

                DynamicObject user = BusinessDataServiceHelper.loadSingle(creatorid,"bos_user");
                String creator =user.getString("username");

                logger.info("oy==办结：flowid:"+flowid+"creater:"+creator);
                //测试
                dealToFin(flowid,creator,context);


            }
        }
    }

    /**
     * 转办结
     * @param flowid 流程id
     * @param user 发送对象
     */
    public void dealToFin(String flowid,String user,String context){
        String url = "";
        String requestJsonStr="";
        String returnResultStr = "";
        String operResult="";
        String message="";
        String pcurl = "";
        String appurl = "";
        QFilter qFilter = new QFilter("number", QCP.like, "OA");
        DynamicObject dynobj= BusinessDataServiceHelper.loadSingle("msg_channel","zmee_dealtodo",new QFilter[]{qFilter});
        url = dynobj.getString("zmee_dealtodo");
        //获取pc/app地址
        QFilter qFilter2 = new QFilter("zmee_flowid", QCP.in, flowid);
        QFilter qFilter3 = new QFilter("zmee_messagetype", QCP.not_in, "deleteToDo");
        DynamicObject dailyreimbursebills = BusinessDataServiceHelper.loadSingle("zmee_log_oapush","fid,zjmi_request",new QFilter[]{qFilter2});
        if (dailyreimbursebills!=null){
            String request =  dailyreimbursebills.getString("zmee_request");
            String pckey = "\"pcurl\":\"";
            String appkey = "\"appurl\":\"";
            String duan = "\",\"";
            int pcindex = request.indexOf(pckey);
            int appindex = request.indexOf(appkey);
            //存在pcurl/appurl地址
            if (pcindex!=-1||appindex!=-1){
                String pcstring = request.substring(pcindex);
                String appstring = request.substring(appindex);
                int pcduan = pcstring.indexOf(duan);
                int appduan = appstring.indexOf(duan);
                pcurl = pcstring.substring(0,pcduan).replace(pckey,"");
                appurl = appstring.substring(0,appduan).replace(appkey,"");
            }
        }
        //拼接参数
        JSONObject requestJson = new JSONObject();
        try {
            //异构系统标识
            requestJson.put("syscode", "hn_opc");
            //流程实例id
            requestJson.put("flowid", flowid);
            //流程标题
            requestJson.put("requestname", context);
            //流程类型名称
            requestJson.put("workflowname", "优采云待办");
            //流程处理状态  4：办结
            requestJson.put("isremark", "4");
            //流程查看状态  0：未读
            requestJson.put("viewtype", "1");
            //接收人账号
            requestJson.put("receiver", user);
            //时间戳字段
            requestJson.put("receivets", String.valueOf(System.currentTimeMillis()));
            //PC地址
            requestJson.put("pcurl", pcurl);
            //APP地址
            requestJson.put("appurl", appurl);
            logger.info("oy==办结：参数:"+requestJson);

            String returnResult = postData2ofs(url,requestJson.toString()); //调用OA接口
            if(returnResult==null|| StringUtils.equals("",returnResult)){
                return;
            }
            requestJsonStr=requestJson.toString();
            JSONObject returnResultObj=JSONObject.fromObject(returnResult);
            returnResultStr=returnResult.toString();
            //操作结果
            operResult=returnResultObj.getString("operResult");
            message=returnResultObj.getString("message");
            logger.info(message);
        }catch (Exception e){
            logger.info("oy==办结：调用oa接口报错:"+e.getMessage());
        }
    }


    /**
     *发送请求
     * @param posturl 请求地址
     * @param param 参数
     * @return
     */
    public String postData2ofs(String posturl, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(serverurl + posturl);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            //获取返回值
            JSONObject object = JSONObject.fromObject(result);
            String returnResult = object.toString();
            return returnResult;
        } catch (Exception var7) {
            logger.error("zjmi.cloud.fi.thirdcapitalsys.plugins.op.DealToFinPlugin,发送 POST请求出现异常！", var7.getMessage());
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }
}

